//
//  BVRegisViewController.h
//  AssistantCloud1
//
//  Created by YYKJ on 2017/4/18.
//  Copyright © 2017年 YYKJ. All rights reserved.
//

#import "BVCaptchaButton.h"
#define CAPTCHA_TIMEOUT 1.0

@interface BVCaptchaButton ()

@property (nonatomic, strong) NSTimer *buttonTextTimer;
@property (nonatomic) NSUInteger captchaButtonText;
@property (nonatomic) NSUInteger initialButtonText;

@end

@implementation BVCaptchaButton
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        self.layer.cornerRadius = 3;
        self.layer.masksToBounds = YES;
    }
    return self;
}
- (void)setCountdown:(NSUInteger)countdownTime {
    
    _captchaButtonText = countdownTime;
    _initialButtonText = countdownTime;
    [self addTarget:self action:@selector(sendCaptcha:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)sendCaptcha:(BVCaptchaButton *)sender {
    [self startButtonTextTimer];
    sender.backgroundColor = [UIColor grayColor];
    sender.userInteractionEnabled = NO;
    _buttonTextTimer = [NSTimer scheduledTimerWithTimeInterval: CAPTCHA_TIMEOUT target:self selector:@selector(startButtonTextTimer) userInfo:nil repeats:YES];
}

- (void)startButtonTextTimer {
    
    if (_captchaButtonText > 0) {
        [UIView performWithoutAnimation:^{
            [self setTitle:[NSString stringWithFormat:@"%ld%@", _captchaButtonText, @"s重新发送"] forState:UIControlStateNormal];
            [self layoutIfNeeded];
        }];
    }else {
        [UIView performWithoutAnimation:^ {
            [self setBackgroundColor:[UIColor BVBaseOrangeColor]];
            [self setTitle: @"重新发送" forState:UIControlStateNormal];
            [self layoutIfNeeded];
        }];
        [_buttonTextTimer invalidate];
        self.userInteractionEnabled = YES;
        _captchaButtonText = _initialButtonText;
    }
    _captchaButtonText--;
}

@end
